package com.iwthings.speex;


import java.net.InetAddress;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

public class SpeexRecoder extends Thread
{
    private int audioSource;
    private static int sampleRateInHz = 8000;  
    
   
    private static int channelConfig =  AudioFormat.CHANNEL_IN_MONO;   
    private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;  
    private int bufferSizeInBytes = 0;  
    private AudioRecord audioRecord = null;
    private int mPackSize = 160;

     
	@SuppressLint("NewApi")
	public int OpenRecoder(int userid, String ip, int port)
	{

		 String strip;
			try {
				InetAddress myServer = InetAddress.getByName(ip);
				strip = myServer.getHostAddress();	
			} catch (UnknownHostException e) {
				strip = "124.202.151.53";
			}
		int iRet = SpeexJni.GetInstance().OpenSpeexEncoder(userid, strip, port);
		if(iRet < 0)
		{
			return -1;
		}
		audioSource = MediaRecorder.AudioSource.MIC ; 	 
		bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,  
		                channelConfig, audioFormat);  
		audioRecord = new AudioRecord(audioSource, sampleRateInHz,  
		                channelConfig, audioFormat, bufferSizeInBytes); 
		
		
		this.start();
		
		return 0;
	}
	
	@SuppressLint("NewApi")
	public int CloseRecoder()
	{
	
		this.interrupt();
		while(this.isAlive())
		{
			this.interrupt();
		}
		if(audioRecord != null)
		{
			audioRecord.stop();
			audioRecord.release();
			audioRecord = null;
		}
		SpeexJni.GetInstance().CloseSpeexEncoder();

	
		return 0;
	}
	
	public void run()
	{	
		if(audioRecord == null)
		{
			return ;
		}
		
		short[] audiodata = new short[mPackSize];
        int readsize = 0;
        SpeexCache.GetInstance().RemoveAll();
        
        audioRecord.startRecording();
        while (!this.isInterrupted() ) 
        {  	
            readsize = audioRecord.read(audiodata, 0, mPackSize); 
          
            if (AudioRecord.ERROR_INVALID_OPERATION != readsize) 
            { 
            	
            	if(SpeexCache.GetInstance().GetSize() > 0)
            	{
            		short[] play = SpeexCache.GetInstance().GetCacheAt(0);
            		SpeexCache.GetInstance().RemoveAt(0); 		   		
            		SpeexJni.GetInstance().SpeexEncode(audiodata, play);				
            	}
            	else
            	{
            		SpeexJni.GetInstance().SpeexEncode(audiodata, null);	
            	}
   	
            }         
            else
            {
            	break;
            }
        }    
	}
	
	 
}
